package com.fj.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author fj
 * @date 2023/12/11 16:50
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        //绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置通道为非阻塞
        serverSocketChannel.configureBlocking(false);
        //注册到selector，关心事件为accept
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            if (selector.select(1000) == 0){
                System.out.println("1秒内无连接");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
//                    SelectableChannel channel = selectionKey.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("连接成功("+socketChannel.hashCode()+")");
                    //设置客户端为非阻塞
                    socketChannel.configureBlocking(false);
                    //注册客户端为非阻塞
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (selectionKey.isReadable()){
                    try{
                        SocketChannel channel = (SocketChannel)selectionKey.channel();
                        ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                        int read = channel.read(byteBuffer);
                        if (read == -1){
                            //read等于-1说明是客户端调用close正常退出时发送的read事件
                            selectionKey.cancel();
                        }else {
                            System.out.println(new String(byteBuffer.array()));
                        }
                    }catch (IOException e){
                        e.printStackTrace();
                        //cancel为了取消掉主动断开连接的客户端断开时触发的read事件
                        selectionKey.cancel();
                    }
                }
                //移除key
                iterator.remove();
            }
        }
    }
}
